package com.sunday.fangdaifu.activity.main;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.reflect.TypeToken;
import com.sunday.common.action.Logout;
import com.sunday.common.adapter.MainFragmentPagerAdapter;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.model.Version;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.volley.Request;
import com.sunday.common.volley.RequestQueue;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.common.widgets.ViewPager;
import com.sunday.fangdaifu.R;
import com.sunday.fangdaifu.activity.login.LoginActivity;
import com.sunday.fangdaifu.base.MyApplication;
import com.sunday.fangdaifu.common.ApiClient;
import com.sunday.fangdaifu.common.ApiServiceImpl;
import com.sunday.fangdaifu.common.Const;
import com.sunday.fangdaifu.model.Member;
import com.sunday.fangdaifu.service.LocationService;
import com.sunday.fangdaifu.utils.SharePerferenceUtils;
import com.umeng.update.UpdateDialogActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.R.attr.version;
import static android.support.v4.content.PermissionChecker.PERMISSION_GRANTED;

/**
 * Created by yun_sheng on 2017/6/28.
 */

public class MainActivity extends BaseActivity implements ApiServiceImpl.HttpResponseInterface {

    @Bind({R.id.tab1, R.id.tab2, R.id.tab3, R.id.tab4})
    List<TextView> tabViews;
    @Bind(R.id.bottom_menu)
    LinearLayout bottomMenu;
    @Bind(R.id.content)
    ViewPager viewPager;

    private ArrayList<Fragment> fragments;
    private Member member;
    private Context mContext;
    private int pageNo = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        pageNo = getIntent().getIntExtra("pageNo", 0);
        mContext = this;
        member = (Member) SharePerferenceUtils.getIns().getOAuth();
        MyApplication.getInstance().setMembe(member);
        fragments = new ArrayList<>(4);
        fragments.add(IndexFragment.newInstance());
        fragments.add(TaskFragment.newInstance());
        fragments.add(DateFragment.newInstance());
        fragments.add(MyFragment.newInstance());
        tabViews.get(pageNo).setSelected(true);
        viewPager.setCurrentItem(pageNo, false);
        viewPager.setAdapter(new MainFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        viewPager.setOffscreenPageLimit(4);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < tabViews.size(); i++) {
                    tabViews.get(i).setSelected(false);
                }
                tabViews.get(position).setSelected(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tabViews.get(pageNo).setSelected(true);
        viewPager.setCurrentItem(pageNo, false);
        checkAppPermission();
        checkUpdate();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        pageNo = getIntent().getIntExtra("pageNo", 0);
        tabViews.get(pageNo).setSelected(true);
        viewPager.setCurrentItem(pageNo, false);
    }

    @OnClick({R.id.tab1, R.id.tab2, R.id.tab3, R.id.tab4})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab1:
                viewPager.setCurrentItem(0, false);
                break;
            case R.id.tab2:
                viewPager.setCurrentItem(1, false);
                break;
            case R.id.tab3:
                viewPager.setCurrentItem(2, false);
                break;
            case R.id.tab4:
                viewPager.setCurrentItem(3, false);
                break;
        }
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                MyApplication.getInstance().getRequestQueue().cancelAll(new RequestQueue.RequestFilter() {
                    @Override
                    public boolean apply(Request<?> request) {
                        return false;
                    }
                });
                finish();
                System.exit(1);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onEvent(Logout event) {
        finish();
    }

    private void checkAppPermission() {
        PackageManager pkgManager = getPackageManager();
        //读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(WRITE_EXTERNAL_STORAGE, getPackageName()) == PERMISSION_GRANTED;

        //read phone state用于获取 imei 设备信息
        boolean phoneStatePermission =
                pkgManager.checkPermission(READ_PHONE_STATE, getPackageName()) == PERMISSION_GRANTED;

        //获取位置权限
        boolean locationWifiPermission = pkgManager.checkPermission(ACCESS_COARSE_LOCATION, getPackageName()) == PERMISSION_GRANTED;
        boolean locationGPSPermission = pkgManager.checkPermission(ACCESS_FINE_LOCATION, getPackageName()) == PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneStatePermission || !locationWifiPermission || !locationGPSPermission) {
            ActivityCompat.requestPermissions(this, new String[]{
                    WRITE_EXTERNAL_STORAGE, READ_PHONE_STATE, ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION
            }, 0);
        } else {
            // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
            MyApplication.getInstance().requestLocation();

        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 0:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
                    MyApplication.getInstance().requestLocation();
                } else {
                    //checkMMS();
                    show();
                }
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //权限申请失败则跳转至设置
    private void show() {
        final UIAlertView view = new UIAlertView(mContext, "温馨提示", "权限已被关闭，是否需要重新设置", "取消", "确定");
        view.setClicklistener(new UIAlertView.ClickListenerInterface() {
            @Override
            public void doLeft() {
                view.dismiss();
            }

            @Override
            public void doRight() {
                view.dismiss();
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        view.show();
    }

    private void checkUpdate() {
        ApiClient.getApiService().checkUpdate(1, DeviceUtils.getVersionCode(getApplicationContext()), this, new TypeToken<Version>() {
        }.getType());
    }

    @Override
    protected void onResume() {
        super.onResume();
        member = (Member) SharePerferenceUtils.getIns().getOAuth();
        if (member != null) {
            MyApplication.getInstance().setMembe(member);
        }
    }

    public void setPageNo(int pageNo) {
        tabViews.get(pageNo).setSelected(true);
        viewPager.setCurrentItem(pageNo, false);
    }

    public void gotoKnowledgePage() {
        setPageNo(2);
        ((DateFragment) fragments.get(2)).viewPager.setCurrentItem(2);
    }

    public void gotoFeedBack() {
        setPageNo(1);
        ((TaskFragment) fragments.get(1)).imgViewPager.setCurrentItem(0);
    }


    @Override
    public void onResponce(String key, Object result) {
        if (isFinish) {
            return;
        }
        final ResultDO<Version> resultDO= (ResultDO<Version>) result;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(mContext, UpdateDialogActivity.class);
                intent.putExtra("version", resultDO.getResult());
                startActivity(intent);
            }
        }, 2000);
    }

    @Override
    public void onFailure() {
        ToastUtils.showToast(mContext, "网络连接错误");
    }
}
